'''
Date: 2023-12-01 12:19:01
Author: WT-W-PC
LastEditors: WT-W-PC
LastEditTime: 2023-12-04 13:16:12
Description: 
junziyun获取链接、签到、获取信息、签到功能
'''

from robustreq import ReqRobot
import json
import utils
from bs4 import BeautifulSoup
import re


class JuziyunRobot(ReqRobot):
  def __init__(self, url_list, email, passwd, retries=20):
    super().__init__(retries)
    self.juziyun_url_list = url_list
    # juziyun链接
    self.juziyun_url = ''
    # 认证地址
    self.auth_url = ''
    # 认证后跳转地址
    self.redirect_url = ''
    # 签到地址
    self.checkin_url = ''
    self.email = email
    self.passwd = passwd
    self._max_retries = 3
    self.remaining_days = ''
    self.surplus_flow = ''
    self.special_offers = ''
    self.discount_time = ''
    self.juziyun_url_list_new = []
    
  # 获取第一个访问顺畅的链接
  def getlinkbysmoothaccess(self, timeout=None):
    result = False
    # 重置最大访问次数为3
    self._max_retries = 3
    
    for juziyun_url in self.juziyun_url_list:
        log_msg = f'Start visiting link {str(juziyun_url)}.'
        self._log.info(log_msg)
        result, resp = self.reqget(juziyun_url, timeout)
        
        if result:
          log_msg = f'The first link to access smoothly is {str(juziyun_url)}.'
          self._log.info(log_msg)
          self.juziyun_url = juziyun_url
          break
        else:
          log_msg = f'Unable to access {str(juziyun_url)} normally.'
          self._log.info(log_msg)

    return result

  # 登陆
  def login(self):
    self._max_retries = 30
    self.auth_url = self.juziyun_url + "/auth/login"

    data = {
        "email": self.email,
        "passwd": self.passwd,
        "code": "",
        "remember_me": "",
    }
    
    form_data = json.dumps(data)
    headers = {
      "Content-Type": "application/json;charset=UTF-8"
    }
    self._headers.update(headers)
    
    result, resp = self.reqpost(self.auth_url, form_data)
    if result:
      try:
        re = resp.json()
        msg = str(re['msg'])
        self.login_msg = msg
        if re.get('ret') != 1:
          result = False
      except Exception as e:
        result = False
        log_msg = f"Parsing the results returned by {self.auth_url} failed."
        self.login_msg = log_msg
        self._log.exception(log_msg)
        self._log.exception(e)
    else:
      self.login_msg = 'Network request failed'
    
    log_msg = f"Login {self.auth_url} was {str(result)}"
    self._log.info(log_msg)
    
    if result == False:
      msg = f'Login {self.auth_url} failed. Reason is {self.login_msg}.'
      raise utils.CommonException(msg)
    
    return result
  
  # 跳转并获取最新网址、剩余天数以及优惠信息
  def acquireinfo(self):
    self._max_retries = 30
    self.redirect_url = self.juziyun_url + "/user"
    
    result, resp = self.reqget(self.redirect_url)
    
    log_msg = f"Acquire info from {self.auth_url} was {str(result)}"
    self._log.info(log_msg)
   
    if result:
      soup = BeautifulSoup(resp.text, 'html.parser')
      # 获取最新链接
      a_tag_list = soup.find_all('a')
      for a_tag in a_tag_list:
          name = a_tag.get('name')
          if name != None:
              structure = re.match(r'地址.+', name)
              if structure != None:
                  self.juziyun_url_list_new.append(re.findall(r'http.+', structure.string)[0])
                  
      # 获取剩余天数和剩余流量
      a_tag_list = soup.find_all('div',attrs={"class":"card-body"})
      for a_tag in a_tag_list:
          text = a_tag.get_text()
          if text != None:
              if re.search(r'天\n', text):
                self.remaining_days = text.replace('\n', '')
              elif re.search(r'TB', text):
                self.surplus_flow = text.replace('\n', '')
      
      # 获取优惠信息和活动时间
      a_tag_list = soup.find_all('h5')
      for a_tag in a_tag_list:
          text = a_tag.get_text()
          if text != None:
              if re.search(r'优惠代码', text):
                  self.special_offers = text
              if re.search(r'活动时间', text):
                  self.discount_time = text
                           
    else:
      msg = f'Acquire info from {self.auth_url} failed.'
      raise utils.CommonException(msg)
    
    return result
  
  # 签到
  def signin(self):
    self._max_retries = 30
    self.signin_url = self.juziyun_url + "/user/checkin"
    
    result, resp = self.reqpost(self.signin_url, {})
    if result:
      try:
        re = resp.json()
        msg = str(re['msg'])
        self.signin_msg = msg.encode("utf-8").decode("utf-8")
      except Exception as e:
        result = False
        log_msg = f"Parsing the results returned by {self.signin_url} failed."
        self._log.exception(log_msg)
        self._log.exception(e)
    
    log_msg = f"{self.auth_url} sign-in was {str(result)}"
    self._log.info(log_msg)
    
    if result == False:
      msg = f'{self.auth_url} signin failed.'
      raise utils.CommonException(msg)
    
    return result